import requests
from bs4 import BeautifulSoup


class StockDetail:
    def __init__(self, code, name, price):
        self.code = code  # 股票代码
        self.name = name  # 股票名称
        self.price = price  # 当前价格

    def __repr__(self):
        return f"Stock(code='{self.code}', name='{self.name}', price={self.price})"


class SinaStockService:

    def get_stock_info(self, stock_code) -> StockDetail:

        stock_code = self.convert_stock_code(stock_code)
        url = f"https://finance.sina.com.cn/realstock/company/{stock_code}/nc.shtml"
        AntLogger.infourl)
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36"
        }

        response = requests.get(url, headers=headers)
        response.encoding = "GBK"  # 设置编码格式

        if response.status_code == 200:
            soup = BeautifulSoup(response.text, "html.parser")

            # 获取股票名称
            stock_name = ""
            stock_name_tag = soup.find("h1", id="stockName")
            if stock_name_tag:

                # 提取股票名称
                stock_name_element = stock_name_tag.contents[
                    0
                ].strip()  # 获取h1标签中的第一部分文本作为股票名称
                stock_name = stock_name_element if stock_name_element else None

                # 提取股票名称
                if stock_name_element is None:
                    stock_name_element = stock_name_tag.find("i", class_="c8_name")
                    stock_name = (
                        stock_name_element.text.strip() if stock_name_element else None
                    )

                # 提取股票代码
                stock_code_element = stock_name_tag.find("span")
                stock_code = (
                    stock_code_element.text.strip() if stock_code_element else None
                )

                if stock_name and stock_code:
                    AntLogger.info(f"股票名称: {stock_name}, 股票代码: {stock_code}")
                else:
                    AntLogger.info("股票名称或代码缺失")
            else:
                AntLogger.info("stock_name_tag 不存在")

            # 获取股票当前价格
            price = ""

            # 将信息封装到 Stock 对象并返回
            stock = StockDetail(stock_code, stock_name, price)
            AntLogger.info(f"获取到股票信息:{stock}")
            return stock
        else:
            AntLogger.info("无法获取数据，请检查股票代码或网络连接。")

    def convert_stock_code(self, stock_code: str) -> str:
        """
        转换股票代码格式，例如将 '601933.SH' 转换为 'sh601933'。
        :param stock_code: 原始股票代码（格式如 '601933.SH'）
        :return: 转换后的股票代码（格式如 'sh601933'）
        """
        if not stock_code or "." not in stock_code:
            raise ValueError(f"无效的股票代码: {stock_code}")

        # 拆分代码与后缀
        code, suffix = stock_code.split(".")

        # 转换后缀为小写并拼接
        return f"{suffix.lower()}{code}"
